package com.ebb.activities;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.ebb.R;
import com.ebb.classes.EBBActivity;
import com.ebb.classes.EBBAlert;
import com.ebb.common.EBBCommonUtil;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

public class EBBLogin extends EBBActivity implements OnClickListener {
    private static final String TAG = EBBLogin.class.getCanonicalName();
    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnSignUp;
    private Button btnFbLogin;;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initLayout();
    }

    private void initLayout() {
        this.etUsername = (EditText) findViewById(R.id.username_value);
        this.etPassword = (EditText) findViewById(R.id.password_value);
        
        this.btnLogin = (Button) findViewById(R.id.login_button);
        this.btnSignUp = (Button) findViewById(R.id.signup_button);
        this.btnFbLogin = (Button) findViewById(R.id.fb_login_button);
        
        this.btnLogin.setId(0x1001);
        this.btnSignUp.setId(0x1002);
        this.btnFbLogin.setId(0x1003);
        
        this.btnLogin.setOnClickListener(this);
        this.btnSignUp.setOnClickListener(this);
        this.btnFbLogin.setOnClickListener(this);
	}

	@Override
    public void onClick(View v) {
        switch (v.getId()) {
        case 0x1001:
			Log.i(TAG, "[success] do login");
            doLogin();
            break;
        case 0x1002:
			Log.i(TAG, "[success] do sign up");
            goSignUp();
            break;
        case 0X1003:
        	setIntent("com.ebb.EBBFBLogin");
        	break;
        }
    }

    private void doLogin() {
        String title = "Login";
        if(EBBCommonUtil.isEmptyEditText(etUsername)) {
            EBBAlert.message(0, title, "Please input your username. ");
            etUsername.requestFocus();
            return;
        } else if(EBBCommonUtil.isEmptyEditText(etPassword)){
            EBBAlert.message(0, title, "Please input your password. ");
            etPassword.requestFocus();
            return;
        }         
        ParseUser.logInInBackground(etUsername.getText().toString().trim(), etPassword.getText().toString().trim(), new LogInCallback() {
            @Override
            public void done(ParseUser parseUser, ParseException e) {
                if(e != null) {
                    EBBAlert.message(0, "Login Error", e.getMessage());
                    return;
                }
                setIntent("com.ebb.EBBEchoList");
            }
        });
    }
    
    public void goSignUp() {
        setIntent("com.ebb.EBBSignUp");
    }
}